﻿using Common;
using Common.DataModels;
using MediatR;
using PLC.Domain.Models;
using Serilog;

namespace PLC.Domain.Events.Handlers;
/// <summary>
/// 发送数据的处理着
/// </summary>
public class SendDataHandler:INotificationHandler<SendDataModel>
{
    private readonly HttpHelper _httpHelper;

    public SendDataHandler(HttpHelper httpHelper)
    {
        _httpHelper = httpHelper?? throw new ArgumentNullException(nameof(httpHelper));
    }
    /// <summary>
    /// 推送数据
    /// </summary>
    /// <param name="notification"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    /// <exception cref="Exception"></exception>
    public async Task Handle(SendDataModel notification, CancellationToken cancellationToken)
    {
        var url = Appsettings.app("DataPush", "Url");
        if (string.IsNullOrWhiteSpace(url))
        {
            throw new Exception("数据推送的url不能为空，请检查DataPush的配置 ");
        }
        // 如果没有数据  那么就不推送了
        if (notification.DeviceStatusList.Count==0
            &&notification.DtoProductionDatas.Count==0
            &&notification.DeviceBeatList.Count==0
            &&notification.DeviceYieldRateList.Count==0)
        {
            return;
        }

        //notification.DeviceBeatList[0].Time = 90;
        // 数据推送
        var result = await  _httpHelper.PostAsync<MessageModel>(url,data:notification);
        if (result==null || !result.success)
        {
            Log.Error($"推送数据失败：{result?.msg??"null"},推送内容：{JsonHelper.SerializeObject(notification)}");
        }
    }
}